package edu.stanford.hardon.Tabs;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.location.Location;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ToggleButton;
import android.media.MediaRecorder;
import android.os.Environment;
import edu.stanford.hardon.DatabaseHelper;
import edu.stanford.hardon.MetadataStorage;
import edu.stanford.hardon.R;
import edu.stanford.hardon.TravelCore;
import edu.stanford.hardon.TravelHard;
import edu.stanford.hardon.TravelHardConstants;
import edu.stanford.hardon.Capture.AudioRecorder;
import edu.stanford.hardon.Media.Media;
import edu.stanford.hardon.Media.MediaType;
import edu.stanford.hardon.Media.RichMedia;

public class AudioTab extends GenericTab{

	private ToggleButton recordButton;
	private AudioRecorder recorder;
	
	public AudioTab(int Id, String Text, int iconResourceId, LinearLayout tabLayout, TravelHard th) {
		super(Id, Text, iconResourceId,tabLayout, th);
		// TODO Auto-generated constructor stub
		
		
		this.recordButton = (ToggleButton) tabLayout.findViewById(R.id.record_audio);
		recordButton.setChecked(false);
    	this.recordButton.setOnClickListener(new OnClickListener() {
    		public void onClick(View v) {
    			try {
    				if (recordButton.isChecked()) {
    			        recorder = new AudioRecorder();
    					recorder.record();
    				} else {
    					recorder.stopRecording();
    					saveAudioToDB();
    				}
//    				if(!recording){
//    					recording = true;
//    					recorder.record();
//    				} else {
//    					recording = false;
//    					recorder.stopRecording();
//    				}
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    	});
        
	}

	@Override
	public void startTab() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void stopTab() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setPaused() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setResumed() {
		// TODO Auto-generated method stub
		
	}
	
	private void saveAudioToDB(){
		//final String date = getTimeNow();
		Date date = new Date();
		Double lat = 0.0, lng = 0.0, alt = 0.0;
		if(th.location != null){
			lat = th.location.getLatitude();
			lng = th.location.getLongitude();
			alt = th.location.getAltitude();
		}
		RichMedia audioMedia = new RichMedia(null, TravelHardConstants.TRIP_ID, MediaType.AUDIO, lat, lng, alt, date, null, null, recorder.getAudioFile().getPath());

		DatabaseHelper dbhh = TravelCore.getDBH();
		dbhh.open();
		dbhh.insert(audioMedia);
		dbhh.close();
	}

}
